package com.it.flowable.service.leave.bpm;

import com.it.flowable.common.vo.leave.LeaveBpmParamVO;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 请假流程 启动
 */
@Service
public class BpmLeaveStartProcessServiceReImpl {

    @Resource
    protected ProcessEngine processEngine;
    @Resource
    private BpmLeaveDao bpmLeaveDao;

    //**************************************************************************

    /**
     * 启动一个流程
     *
     * @param processKey 流程Key
     * @return params List<Map < String, Object>> 流程变量
     * @throws
     */
    //**************************************************************************
    public List<Map<String, Object>> startProcess(String processKey, Map<String, Object> params) throws Exception {
        RuntimeService runtimeService = processEngine.getRuntimeService();
        if (processKey == null || "".equals(processKey)) {
            throw new Exception("通过processKey启动流程失败：BpmLeaveProcessServiceReImpl.startProcess，processKey流程主键值为空，请联系管理员");
        }
        BpmLeaveThreadLocalRe.clear();            // 清空线程变量
        BpmLeaveThreadLocalRe.bindData();            // 线程变量初始化
        // 启动流程 暂不关联租户，租户关联会导致报错
        if (params != null) {
//            runtimeService.startProcessInstanceByKeyAndTenantId(processKey, params, "xl");
            ProcessInstance instance = runtimeService.startProcessInstanceByKey(processKey, params);
            bpmLeaveDao.insertActLeaveProcessExtVO(instance.getProcessInstanceId(), params);
        } else {
            throw new Exception("通过processKey启动流程失败：BpmLeaveProcessServiceReImpl.startProcess, params为空！");
//            runtimeService.startProcessInstanceByKeyAndTenantId(processKey,"xl");
//            runtimeService.startProcessInstanceByKey(processKey);
        }

        return BpmLeaveThreadLocalRe.getSessionData(BpmLeaveThreadLocalRe.getThreadLocalDataAll());  // 线程变量转化为Map模式
    }

    public void startProcessByMessage(String processKey,
                                      String processId, Map<String, Object> params) throws Exception {
        RuntimeService runtimeService = processEngine.getRuntimeService();
        if (processKey == null || "".equals(processKey)) {
            throw new Exception("通过processKey启动流程失败：BpmLeaveProcessServiceReImpl.startProcess，processKey流程名称为空，请联系管理员");
        }
        runtimeService.startProcessInstanceByMessageAndTenantId(processKey, processId, params,"admin");

    }

}
